package com.fs.ibox_h.web;

import com.alibaba.fastjson.JSON;
import com.fs.ibox_h.pojo.admin;
import com.fs.ibox_h.servie.adminService;
import com.fs.ibox_h.util.BeanFactory;
import com.fs.ibox_h.util.ResponseDataUtil;
import com.fs.ibox_h.vo.ResponseData;
import com.fs.ibox_h.vo.ResultEnums;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        adminService service = BeanFactory.createBean(adminService.class);
        admin admin = service.selectByUsernameAndPwd(username, password);

        PrintWriter writer = response.getWriter();
        ResponseData responseData = null;
        String json = null;
        if (admin != null) {
            responseData = ResponseDataUtil.buildOk(admin);
        } else {
            responseData = ResponseDataUtil.buildOk(ResultEnums.FAIL_ADMIN);
        }
        json = JSON.toJSONString(responseData);
        writer.print(json);
        writer.flush();

    }
}
